function mle = SMLE_v2(params,data,random_draws,random_draws2,alpha_draws, num_drugs, num_periods, id, outside, S)
%SMLE Computes likelihood function given data and parameter guess

    delta = params(1:3);
    
    alpha = params(4);
    gamma = params(5);
    mu1 = params(6);
    sigma1 = params(7);
    mu2 = params(8);
    sigma2 = params(9);
    sigma_alpha = params(10);
    
    random_draws = random_draws * sigma1 + mu1 + random_draws2 * sigma2 + mu2;
    alpha_draws = sigma_alpha * alpha_draws; % scale this as well
    
    % STEP 1: transform data into ID, quarter u_ij based on parameters
    % Basic_part: drug quality - alpha * copay
    u = delta(data(:,3)) + gamma * data(:,6);
    % repmat sideways and add random draw rows; alpha_draw is just one row
    % corresponding to the person's ID (column 1)
    u = repmat(u,1,S) - ...
        (alpha+alpha_draws(data(:,1),:)) .* repmat(data(:,5),1,S) + ...
        random_draws(data(:,3) + num_drugs * (data(:,1) - 1), :);
    
    % STEP 2: aggregate and compute SMLE
    eu = exp(u);
    probs = zeros(size(outside,1),S);
    
    for i=1:S
        groupsum = 1 + accumarray(id, eu(:,i));
        eu_chosen = eu(:,i) .* data(:,4);
        chosen_sum = accumarray(id,eu_chosen);
        p = ((1 - outside) .* chosen_sum + outside * 1) ./ groupsum;
        
        probs(:,i) = p;
    end

    
    mean_probs= mean(probs,2);
    mle = sum(log(mean_probs));
end

